package com.demo.jfinal.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.core.sgip.client.SGIP2UpClient;
import com.demo.jfinal.model.ApiOrders;
import com.demo.jfinal.model.GatewayConfig;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Redis;

/**
 * 向供应商发送任务
 * 
 * @author Guoxing
 *
 */
public class Request2UpJob implements Job {
	private static Logger log = Logger.getLogger(Request2UpJob.class);

	/*
	 * 从表里拿数据向运营商发送
	 */
	@Before(Tx.class)
	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

		log.info("向上游发送任务正在执行：" + System.currentTimeMillis());

		Date date = new Date();
		// 获取当前时间之前状态为未发送 的订单
		List<ApiOrders> lists = ApiOrders.dao.find(
				"select * from sms_api_orders where 1=1 and STATE='N' and GATEWAY_ID = '9' and ORDER_DATE <= ? ", date);
		if (lists.size() == 0 || lists == null || lists.isEmpty()) {
			log.info("Request2UpJob无数据处理");
			return;
		}
		Db.update(
				"update sms_api_orders set STATE  = 'P' where 1=1 and STATE='N' and GATEWAY_ID = '9' and ORDER_DATE <= ? ",
				date);

		List<String> listUserNumber = new ArrayList<String>();

		// 向广西联通运营商发送
		// String gatewayId = lists.get(i).getStr("GATEWAY_ID");
		GatewayConfig gatewayConfig = Redis.use("SGIP").get("gatewayConfig" + 9);
		if (gatewayConfig == null) {
			gatewayConfig = GatewayConfig.dao.findFirst("select * from sms_gateway_config where 1=1 and ID= ? ", 9);
		}
		if (gatewayConfig == null) {
			log.info("向上游发送未未获取到ID=" + 9 + "的供应商信息");
			return;
		}

		String appkey = gatewayConfig.getStr("APP_KEY");
		String securtyKey = gatewayConfig.getStr("SECURTY");
		String sgipIp = gatewayConfig.getStr("SGIP_IP");
		String sgipPort = gatewayConfig.getStr("SGIP_PORT");

		for (int i = 0; i < lists.size(); i++) {
			ApiOrders apiorders = lists.get(i);

			String phone = apiorders.getStr("PHONE_NO");
			String content = apiorders.getStr("CONTENT");

			listUserNumber.add(phone);

			try {
				SGIP2UpClient.sendMsg(appkey, securtyKey, sgipIp, sgipPort, listUserNumber, content,
						apiorders);
				listUserNumber.clear();
			} catch (Exception e) {
				log.error("调用sendMsg异常" + e);
				e.printStackTrace();
			}
			apiorders = null;
			// lists.get(i).set("STATE", "S");
		}

		// 把发送的数据放在interfance表里

		// String sql = "insert into sms_gateway_interface(ORDER_ID,
		// PHONE_NO,GATEWAY_ID,SEND_DATE,STATE) values(?,?,?,?,?)";
		// Db.batch(sql, "ORDER_ID, PHONE_NO,GATEWAY_ID,SEND_DATE,STATE", lists,
		// lists.size());

	}

}
